package com.tkmybatis.hfy.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MapUtil {

	public static Map<String, Object> object2Map(Object obj) {
		Map<String, Object> map = new HashMap<>();
		if (obj == null) {
			return map;
		}
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		try {
			for (Field field : fields) {
				field.setAccessible(true);
				if (!"serialVersionUID".equals(field.getName())) {
					map.put(field.getName(), field.get(obj));
				}
			}
		} catch (Exception e) {
			log.error("error:", e);
		}
		return map;
	}
	
	//Map转Object
	public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
	    if (map == null)
	        return null;
	    Object obj = beanClass.newInstance();
	    Field[] fields = obj.getClass().getDeclaredFields();
	    for (Field field : fields) {
	        int mod = field.getModifiers();
	        if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
	            continue;
	        }
	        field.setAccessible(true);
	        if (map.containsKey(field.getName())) {
	            field.set(obj, map.get(field.getName()));
	        }
	    }
	    return obj;
	}
	
	public static List<Object> mapToObjects(List<Map<String, Object>> maps, Class<?> beanClass) throws Exception {
	    List<Object> objects = new ArrayList<>();
		for(Map<String, Object> map : maps) {
			objects.add(mapToObject(map, beanClass));
	    }
	    return objects;
	}

	public static Map<String, Object> toReplaceKeyLow(Map<String, Object> map) {
		Map re_map = new HashMap();
		if (re_map != null) {
			Iterator var2 = map.entrySet().iterator();
			while (var2.hasNext()) {
				Entry<String, Object> entry = (Entry) var2.next();
				re_map.put(underlineToCamel((String) entry.getKey()), map.get(entry.getKey()));
			}
			map.clear();
		}
		return re_map;
	}
	
	public static List<Map<String, Object>> toReplaceKeyLow(List<Map<String, Object>> maps) {
		List<Map<String, Object>> resultMaps = new ArrayList<>();
		for(Map<String, Object> map : maps) {
			resultMaps.add(toReplaceKeyLow(map));
		}
		return resultMaps;
	}
	
	public static String underlineToCamel(String param){
    	param = param.toLowerCase();
        if (param==null||"".equals(param.trim())){
            return "";
        }
        StringBuilder sb=new StringBuilder(param);
        Matcher mc= Pattern.compile("_").matcher(param);
        int i=0;
        while (mc.find()){
            int position=mc.end()-(i++);
            sb.replace(position-1,position+1,sb.substring(position,position+1).toUpperCase());
        }
        return sb.toString();
    }
}
